package com.example.administrator.xxnapp.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.xxnapp.R;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.math.BigDecimal;


/**
 * Created by asmin on 2017/4/7.
 */

public class DownLoadDialog extends Dialog implements View.OnClickListener{
    private static final String TAG = "TipsDialog";
    private Context context;
    private ProgressBar mPB;
    private TextView mTVsize,mTVupdate,mTVinto;
    private File loadApp;
    private boolean success = false;

    public DownLoadDialog(Context context) {
        super(context, R.style.NoDialogTitleView);
        this.context = context;
        setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_dialog_layout);
        initViews();

//        setListener();
    }

    @Override
    public void show() {
        super.show();
        setParams(0.75);
    }

    private void setParams(double rote) {
        Window window = this.getWindow() ;
        DisplayMetrics d = context.getResources().getDisplayMetrics();
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (d.widthPixels * rote); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
    }

    private void initViews() {
        mPB = (ProgressBar) findViewById(R.id.download_dialog_layout_progressbar);
        mTVsize = (TextView) findViewById(R.id.download_dialog_layout_TV_size);
        mTVupdate = (TextView) findViewById(R.id.download_dialog_layout_TV_sure);
        mTVinto = (TextView) findViewById(R.id.download_dialog_layout_TV_into);
        mTVinto.setVisibility(View.GONE);
        mTVupdate.setVisibility(View.VISIBLE);
    }

    public void downLoadApp(final String loadUrl){
        mTVupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //有新版本
                loadApp(loadUrl);
            }
        });
    }

    private void loadApp(final String loadUrl) {
        Log.e(TAG, "loadApp: "+loadUrl);
        mTVupdate.setText("正在更新");
        mTVupdate.setClickable(false);

        OkGo.<File>get(loadUrl)
                .execute(new FileCallback(Environment.getExternalStorageDirectory()+"/"+context.getPackageName(),"CDSS.apk") {
                    @Override
                    public void onError(Response<File> response) {
                        super.onError(response);
                        Toast.makeText(context, "当前网络不可用，无法从服务器获取版本信息，请确保网络连接正常，或未开通权限，请在手机设置中开启应用权限后重试。", Toast.LENGTH_LONG).show();
                        mTVupdate.setVisibility(View.VISIBLE);
                        mTVupdate.setClickable(true);
                        mTVupdate.setText("立即下载");
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        super.downloadProgress(progress);
                        mPB.setProgress((int) (100*progress.fraction));
                        mTVsize.setText(getFormatSize(progress.currentSize*progress.fraction)+"/"+getFormatSize(progress.totalSize));
                    }


                    @Override
                    public void onSuccess(Response<File> response) {
                        loadApp = response.body();
                        success = true;
                        Intent intent = getFileIntent(response.body());
                        context.startActivity(intent);
                        dismiss();
                    }
                });
    }

    public Intent getFileIntent(File file) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri photoURI = getUri(intent,file);
        intent.setDataAndType(photoURI, "application/vnd.android.package-archive");
        return intent;
    }

    private Uri getUri(Intent intent, File file) {
        Uri uri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判断版本是否在7.0以上
            uri =
                    FileProvider.getUriForFile(context,
                            context.getPackageName() + ".provider",
                            file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "B";
            return "0.0M";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
//            return  "0.0M";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       /* if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
//            this.dismiss();
            return true;
        }*/
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
        }
    }

    private OnTipsDialogClickListener onTipsDialogClickListener;

    public void setOnTipsDialogClickListener(OnTipsDialogClickListener onTipsDialogClickListener) {
        this.onTipsDialogClickListener = onTipsDialogClickListener;
    }

    public interface OnTipsDialogInterfaceClickListener{
        void onSureClick();
        void onCancleClick();
    }

    public static abstract class OnTipsDialogClickListener implements OnTipsDialogInterfaceClickListener{
        @Override
        public void onCancleClick() {
        }
    }
}